use std::{
    collections::HashMap,
    ops::Deref,
    sync::{Arc, Mutex},
};

use model_graph_types::{
    container::workflow::{
        WorkflowBlock, WorkflowBlockBody, WorkflowBlockChain, WorkflowBlockExecuteResult,
        WorkflowBlockRef, WorkflowEngineRunOptions, WorkflowResult,
    },
    modeling::Value,
};

use crate::workflow::{
    blocks::{for_each, if_else, return_statement, start, statements, try_catch},
    context::WorkflowContext,
};

pub async fn execute(
    block: &WorkflowBlockRef,
    context: Arc<Mutex<WorkflowContext>>,
) -> anyhow::Result<WorkflowBlockExecuteResult> {
    let (id, statement) = {
        let block = block.lock().map_err(|err| anyhow::anyhow!("{}", err))?;
        (block.id.clone(), block.body.clone())
    };
    //执行

    //
    let result = match statement {
        WorkflowBlockBody::Start(body) => start::execute(&body, context.clone())?,
        WorkflowBlockBody::Return(body) => return_statement::execute(&body, context.clone())?,
        WorkflowBlockBody::IfElse(body) => if_else::execute(&body, context.clone()).await?,
        WorkflowBlockBody::ForEach(body) => for_each::execute(&id, &body, context.clone()).await?,
        WorkflowBlockBody::TryCatch(body) => try_catch::execute(&body, context.clone())?,
        WorkflowBlockBody::Statement(body) => {
            statements::execute(&id, &body, context.clone()).await?
        }
        _ => WorkflowBlockExecuteResult::succeed(),
    };

    Ok(result)
}
